package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"net/http"
	"strings"
)

// TraceId 自动增加requestId
func TraceId(trafficKey string) gin.HandlerFunc {
	return func(c *gin.Context) {
		if c.Request.Method == http.MethodOptions {
			c.Next()
			return
		}
		traceId := c.GetHeader(trafficKey)
		if len(traceId) == 0 {
			traceId = c.GetHeader(strings.ToLower(trafficKey))
		}
		if len(traceId) == 0 {
			traceId = uuid.New().String()
		}
		c.Request.Header.Set(trafficKey, traceId)
		c.Set(trafficKey, traceId)
		//c.Set(pkg.LoggerKey,
		//	logger.NewHelper(logger.DefaultLogger).
		//		WithFields(map[string]interface{}{
		//			trafficKey: requestId,
		//		}))
		c.Next()
	}
}
